package com.gcb.common.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.gcb.common.exception.AuthException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class TokenUtil {

    @Value("${gcb.tokenKey}")
    private String tokenKey;

    @Value("${gcb.tokenExp}")
    private Integer tokenExp;

    public String getToken(Long id) {
        DateTime now = DateTime.now();
        DateTime expTime = now.offsetNew(DateField.HOUR, tokenExp);
        Map<String, Object> payload = new HashMap<>();
        // 签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        // 过期时间
        payload.put(JWTPayload.EXPIRES_AT, expTime);
        // 生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        payload.put("id", id);
        return JWTUtil.createToken(payload, tokenKey.getBytes());
    }

    public Long checkToken(String token) {
        try {
            boolean verify = JWTUtil.verify(token, tokenKey.getBytes());
            if (!verify) {
                throw new AuthException("token失效");
            }
        } catch (Exception e) {
            throw new AuthException("token失效");
        }

        JWT jwt = JWTUtil.parseToken(token);
        Object id = jwt.getPayload("id");
        return Long.parseLong(String.valueOf(id));
    }
}
